package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.LeaseAgreementService;
import com.atguigu.lease.web.admin.vo.agreement.AgreementQueryVo;
import com.atguigu.lease.web.admin.vo.agreement.AgreementVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liubo
 * @description 针对表【lease_agreement(租约信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class LeaseAgreementServiceImpl extends ServiceImpl<LeaseAgreementMapper, LeaseAgreement> implements LeaseAgreementService {

    @Autowired
    private LeaseAgreementMapper leaseAgreementMapper;

    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    @Autowired
    private RoomInfoMapper roomInfoMapper;

    @Autowired
    private PaymentTypeMapper paymentTypeMapper;

    @Autowired
    private LeaseTermMapper leaseTermMapper;

    @Override
    public boolean updateStatusByIdCustom(Long id, LeaseStatus status) {
        // 参数校验
        if (id == null) {
            log.error("租约id为空");
            return false;
        }

        if (status == null) {
            log.error("状态参数为空");
            return false;
        }


        LeaseAgreement leaseAgreement = this.getById(id);
        // 判断是否被删除
        if (leaseAgreement.getIsDeleted() == 1) {
            log.error("租约信息已被删除, id: {}" + id);
            return false;
        }
        // 更新租约状态
        leaseAgreement.setStatus(status);

        return true;
    }

    @Override
    public boolean removeByIdCustom(Long id) {
        if (id == null) {
            log.error("租约id为空");
            return false;
        }

        // 查询租约是否存在
        LeaseAgreement leaseAgreement = this.getById(id);
        if (leaseAgreement == null) {
            log.error("租约信息不存在, id: {}" + id);
            return false;
        }

        // 如果已经被删除，直接返回成功
        if (leaseAgreement.getIsDeleted() == 1) {
            return true;
        }

        // 判断租约状态是否允许删除
        // 已签约或续约待确认的租约不允许直接删除
        if (LeaseStatus.SIGNED.getCode() == leaseAgreement.getStatus().getCode() ||
                LeaseStatus.RENEWING.getCode() == leaseAgreement.getStatus().getCode()) {
            log.error("当前租约状态不允许删除, id: {}, status: {}");
            return false;
        }

        try {
            // 执行软删除，设置is_deleted=1
            leaseAgreement.setIsDeleted((byte) 1);
            return this.updateById(leaseAgreement);
        } catch (Exception e) {
            log.error("删除租约信息失败, id: {}" + id, e);
            throw e; // 事务回滚
        }
    }

    @Override
    public AgreementVo getByIdCustom(Long id) {
        if (id == null) {
            log.error("租约id为空");
            return null;
        }

        // 查询租约基本信息
        LeaseAgreement leaseAgreement = this.getById(id);
        if (leaseAgreement == null || leaseAgreement.getIsDeleted() == 1) {
            log.error("租约信息不存在或已被删除, id: {}" + id);
            return null;
        }

        // 组装返回对象
        AgreementVo agreementVo = new AgreementVo();
        BeanUtils.copyProperties(leaseAgreement, agreementVo);

        // 查询关联的公寓信息
        if (leaseAgreement.getApartmentId() != null) {
            ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(leaseAgreement.getApartmentId());
            if (apartmentInfo != null && apartmentInfo.getIsDeleted() == 0) {
                agreementVo.setApartmentInfo(apartmentInfo);
            }
        }

        // 查询关联的房间信息
        if (leaseAgreement.getRoomId() != null) {
            RoomInfo roomInfo = roomInfoMapper.selectById(leaseAgreement.getRoomId());
            if (roomInfo != null && roomInfo.getIsDeleted() == 0) {
                agreementVo.setRoomInfo(roomInfo);
            }
        }

        // 查询关联的支付方式
        if (leaseAgreement.getPaymentTypeId() != null) {
            PaymentType paymentType = paymentTypeMapper.selectById(leaseAgreement.getPaymentTypeId());
            if (paymentType != null && paymentType.getIsDeleted() == 0) {
                agreementVo.setPaymentType(paymentType);
            }
        }

        // 查询关联的租期信息
        if (leaseAgreement.getLeaseTermId() != null) {
            LeaseTerm leaseTerm = leaseTermMapper.selectById(leaseAgreement.getLeaseTermId());
            if (leaseTerm != null && leaseTerm.getIsDeleted() == 0) {
                agreementVo.setLeaseTerm(leaseTerm);
            }
        }

        return agreementVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateCustom(LeaseAgreement leaseAgreement) {
        try {
            // 区分新增和修改
            if (leaseAgreement.getId() == null || leaseAgreement.getId() == 0) {
                // 新增租约信息
                return addLeaseAgreement(leaseAgreement);
            } else {
                // 修改租约信息
                return updateLeaseAgreement(leaseAgreement);
            }
        } catch (Exception e) {
            log.error("保存或修改租约信息失败", e);
            throw e; // 事务回滚
        }
    }

    @Override
    public IPage<AgreementVo> pageAppointmentVo(Page<AgreementVo> pageParam, AgreementQueryVo queryVo) {
        // 构建查询条件
        LambdaQueryWrapper<LeaseAgreement> wrapper = new LambdaQueryWrapper<>();

        // 只查询未删除的记录
        wrapper.eq(LeaseAgreement::getIsDeleted, 0);

        if (queryVo != null) {
            // 根据用户姓名模糊查询
            if (StringUtils.hasText(queryVo.getName())) {
                wrapper.like(LeaseAgreement::getName, queryVo.getName());
            }

            // 根据用户手机号码精确查询
            if (StringUtils.hasText(queryVo.getPhone())) {
                wrapper.eq(LeaseAgreement::getPhone, queryVo.getPhone());
            }

            // 根据公寓id查询
            if (queryVo.getApartmentId() != null) {
                wrapper.eq(LeaseAgreement::getApartmentId, queryVo.getApartmentId());
            } else {
                // 如果没有指定公寓id，但指定了地区相关信息，则需要关联公寓表进行查询
                boolean hasRegionFilter = queryVo.getProvinceId() != null ||
                        queryVo.getCityId() != null ||
                        queryVo.getDistrictId() != null;

                if (hasRegionFilter) {
                    // 查询符合区域条件的公寓ID列表
                    LambdaQueryWrapper<ApartmentInfo> apartmentWrapper = new LambdaQueryWrapper<>();
                    apartmentWrapper.eq(ApartmentInfo::getIsDeleted, 0);
                    //省
                    if (queryVo.getProvinceId() != null) {
                        apartmentWrapper.eq(ApartmentInfo::getProvinceId, queryVo.getProvinceId());
                    }
                    //市
                    if (queryVo.getCityId() != null) {
                        apartmentWrapper.eq(ApartmentInfo::getCityId, queryVo.getCityId());
                    }
                    //区
                    if (queryVo.getDistrictId() != null) {
                        apartmentWrapper.eq(ApartmentInfo::getDistrictId, queryVo.getDistrictId());
                    }

                    // 获取符合条件的公寓ID
                    List<ApartmentInfo> apartmentList = apartmentInfoMapper.selectList(apartmentWrapper);
                    if (!apartmentList.isEmpty()) {
                        List<Long> apartmentIds = apartmentList.stream()
                                .map(ApartmentInfo::getId)
                                .collect(Collectors.toList());
                        wrapper.in(LeaseAgreement::getApartmentId, apartmentIds);
                    } else {
                        // 如果没有符合条件的公寓，直接返回空页
                        return new Page<>(pageParam.getCurrent(), pageParam.getSize());
                    }
                }
            }

            // 根据房间号查询
            if (StringUtils.hasText(queryVo.getRoomNumber())) {
                // 先查询符合房间号的房间ID
                LambdaQueryWrapper<RoomInfo> roomWrapper = new LambdaQueryWrapper<>();
                roomWrapper.eq(RoomInfo::getIsDeleted, 0)
                        .like(RoomInfo::getRoomNumber, queryVo.getRoomNumber());

                // 获取房间ID列表
                List<RoomInfo> roomList = roomInfoMapper.selectList(roomWrapper);
                if (!roomList.isEmpty()) {
                    List<Long> roomIds = roomList.stream()
                            .map(RoomInfo::getId)
                            .collect(Collectors.toList());
                    wrapper.in(LeaseAgreement::getRoomId, roomIds);
                } else {
                    // 如果没有找到对应房间，直接返回空页
                    return new Page<>(pageParam.getCurrent(), pageParam.getSize());
                }
            }
        }
        // 执行分页查询
        Page<LeaseAgreement> leaseAgreementPage = new Page<>(pageParam.getCurrent(), pageParam.getSize());
        IPage<LeaseAgreement> leaseAgreementIPage = baseMapper.selectPage(leaseAgreementPage, wrapper);

        // 转换结果
        Page<AgreementVo> agreementVoPage = new Page<>(
                leaseAgreementIPage.getCurrent(),
                leaseAgreementIPage.getSize(),
                leaseAgreementIPage.getTotal());

        if (leaseAgreementIPage.getRecords().isEmpty()) {
            agreementVoPage.setRecords(new ArrayList<>());
            return agreementVoPage;
        }

        // 转换记录为AgreementVo
        List<AgreementVo> agreementVoList = leaseAgreementIPage.getRecords().stream().map(agreement -> {
            AgreementVo agreementVo = new AgreementVo();
            BeanUtils.copyProperties(agreement, agreementVo);

            // 获取公寓信息
            if (agreement.getApartmentId() != null) {
                ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(agreement.getApartmentId());
                if (apartmentInfo != null && apartmentInfo.getIsDeleted() == 0) {
                    agreementVo.setApartmentInfo(apartmentInfo);
                }
            }

            // 获取房间信息
            if (agreement.getRoomId() != null) {
                RoomInfo roomInfo = roomInfoMapper.selectById(agreement.getRoomId());
                if (roomInfo != null && roomInfo.getIsDeleted() == 0) {
                    agreementVo.setRoomInfo(roomInfo);
                }
            }

            // 获取支付方式
            if (agreement.getPaymentTypeId() != null) {
                PaymentType paymentType = paymentTypeMapper.selectById(agreement.getPaymentTypeId());
                if (paymentType != null && paymentType.getIsDeleted() == 0) {
                    agreementVo.setPaymentType(paymentType);
                }
            }

            // 获取租期信息
            if (agreement.getLeaseTermId() != null) {
                LeaseTerm leaseTerm = leaseTermMapper.selectById(agreement.getLeaseTermId());
                if (leaseTerm != null && leaseTerm.getIsDeleted() == 0) {
                    agreementVo.setLeaseTerm(leaseTerm);
                }
            }

            return agreementVo;
        }).collect(Collectors.toList());

        agreementVoPage.setRecords(agreementVoList);

        return agreementVoPage;
    }

    /**
     * 新增租约
     *
     * @param leaseAgreement 租约信息
     * @return 是否新增成功
     */
    private boolean addLeaseAgreement(LeaseAgreement leaseAgreement) {
        // 检查该房间是否已存在有效租约
        if (hasActiveAgreement(leaseAgreement.getRoomId(), null)) {
            return false;
        }

        // 设置软删除标志为未删除
        leaseAgreement.setIsDeleted((byte) 0);
        // 插入新记录
        return this.save(leaseAgreement);
    }

    /**
     * 更新租约
     *
     * @param leaseAgreement 租约信息
     * @return 是否更新成功
     */
    private boolean updateLeaseAgreement(LeaseAgreement leaseAgreement) {
        // 检查要修改的记录是否存在
        LeaseAgreement existingAgreement = this.getById(leaseAgreement.getId());
        if (existingAgreement == null || existingAgreement.getIsDeleted() == 1) {
            return false;
        }

        // 如果更换了房间，检查新房间是否已有有效租约
        if (!existingAgreement.getRoomId().equals(leaseAgreement.getRoomId())) {
            if (hasActiveAgreement(leaseAgreement.getRoomId(), leaseAgreement.getId())) {
                return false;
            }
        }


        // 保持删除标志不变
        leaseAgreement.setIsDeleted(existingAgreement.getIsDeleted());

        // 更新记录
        return this.updateById(leaseAgreement);
    }

    /**
     * 检查房间是否已存在有效租约
     *
     * @param roomId             房间ID
     * @param excludeAgreementId 需要排除的租约ID（修改时使用）
     * @return 是否存在有效租约
     */
    private boolean hasActiveAgreement(Long roomId, Long excludeAgreementId) {
        LambdaQueryWrapper<LeaseAgreement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LeaseAgreement::getRoomId, roomId)
                .eq(LeaseAgreement::getIsDeleted, 0)
                .in(LeaseAgreement::getStatus,
                        Arrays.asList(LeaseStatus.SIGNED,
                                LeaseStatus.WITHDRAWING,
                                LeaseStatus.RENEWING));

        // 如果是修改操作，需要排除当前租约ID
        if (excludeAgreementId != null) {
            wrapper.ne(LeaseAgreement::getId, excludeAgreementId);
        }

        Long count = baseMapper.selectCount(wrapper);
        return count > 0;
    }
}




